
'use strict'

const bcrypt = require('bcrypt')
const dayjs = require('dayjs')

const {
  Sequelize,
  DataTypes,
  Model
} = require('sequelize')
const { sequelize } = require('../utils/db')

class User extends Model { }

User.init({
  //主键：不能重复 不能为空 
  //设计编号系统 id
  //考虑并发 自增长导致报错 
  userId: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  userName: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false,
    //观察者模式
    set(val) {
      const salt = bcrypt.genSaltSync(10)// 10 计算机生成盐的成本  安全系数
      const pwd = bcrypt.hashSync(val, salt)//密码加盐 防止彩虹攻击
      this.setDataValue('password', pwd)
    }
  },
  status: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: true
  },
  role: {
    type: DataTypes.STRING(50),
  },
  createTime: {
    type: DataTypes.DATE, defaultValue: DataTypes.NOW,
    get() {
      return dayjs(this.getDataValue('createTime')).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  updateTime: {
    type: DataTypes.DATE, defaultValue: DataTypes.NOW,
    get() {
      return dayjs(this.getDataValue('updateTime')).format('YYYY-MM-DD HH:mm:ss')
    }
  }
}, {
  sequelize,
  tableName: 'user'
})

module.exports = {
  User
}
